import { useState } from "react";
type ApiFun<TD, TP extends any[]> = (...params: TP) => Promise<TD>;

interface AutoRequestOptions {
  loading?: boolean;
  onSuccess?: (data: any) => void;
}

type AutoRequestResult<TD, TP extends any[]> = [boolean, ApiFun<TD, TP>];

/* 控制loading状态的自动切换hook */
/**
 * 
 * @param fun 
 * @param options 
 * @returns 
 */
export function useAutoRequest<TD, TP extends any[] = any[]>(fun: ApiFun<TD, TP>, options?: AutoRequestOptions): AutoRequestResult<TD, TP> {
  const { loading = false, onSuccess } = options || { loading: false };

  const [requestLoading, setRequestLoading] = useState(loading);

  const runner: ApiFun<TD, TP> = async (...params) => {
    setRequestLoading(true);
    try {
      const res = await fun(...params);
      onSuccess && onSuccess(res);
      return res;
    } finally {
      setRequestLoading(false);
    }
  };

  return [requestLoading, runner];
}